<?php
namespace app\admin\controller;

use app\common\model\AdminUser;
use app\common\model\User as UserModel;
use app\common\controller\AdminBase;
use think\Config;
use think\Db;
use app\common\model\AuthGroupAccess as AuthGroupAccessModel;

/**
 * 用户管理
 * Class AdminUser
 * @package app\admin\controller
 */
class User extends AdminBase
{
    protected $user_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->user_model = new UserModel();
    }

    /**
     * 用户管理
     * @param string $keyword
     * @param int    $page
     * @return mixed
     */
    public function index($keyword = '', $page = 1)
    {
        $map = [];
        if ($keyword) {
            $map['nickname|mobile|email'] = ['like', "%{$keyword}%"];
        }
        $user_list = $this->user_model->where($map)->order('id DESC')->paginate(15, false, ['page' => $page]);

        return $this->fetch('index', ['user_list' => $user_list, 'keyword' => $keyword]);
    }

    /**
     * 添加用户
     * @return mixed
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 保存用户
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
			$data['created_at'] = date('Y-m-d H:i:s',time());
			$data['headimgurl'] = "http://lsjadmin.weilaizhiyuan.com/uploads/logo/img_logo.jpg";


            $data['password'] = md5(md5($data['password']));
            $data['uid'] = 'sj_'.time().str_pad(mt_rand(0, pow(10, 4) - 1), 4, '0', STR_PAD_LEFT);
            unset($data['confirm_password']);

            if(Db::table('lsj_user')->where('email',$data['email'])->find()){
                $this->error('已存在的邮箱');
            }

            Db::startTrans();

            if (Db::table('lsj_user')->insertGetId($data)) {
                if($data['is_author'] == 1){
                    $auth_group_access_model  = new AuthGroupAccessModel();

                    if(!$auth_group_access_model->insert(['uid'=>$data['uid'],'group_id'=>2])){
                        Db::rollback();
                        $this->error('保存失败');
                    }else{
                        Db::commit();
                        $this->success('保存成功');
                    }
                }else{
                    Db::commit();
                    $this->success('保存成功');
                }

            } else {
                Db::rollback();
                $this->error('保存失败');
            }
        }
    }

    /**
     * 编辑用户
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $user = $this->user_model->find($id);

        return $this->fetch('edit', ['user' => $user]);
    }

    /**
     * 更新用户
     * @param $id
     */
    public function update($id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'User');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $user           = $this->user_model->find($id);
                $user->id       = $id;
                $user->username = $data['username'];
                $user->mobile   = $data['mobile'];
                $user->email    = $data['email'];
                $user->status   = $data['status'];
                if (!empty($data['password']) && !empty($data['confirm_password'])) {
                    $user->password = md5($data['password'] . Config::get('salt'));
                }
                if ($user->save() !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除用户
     * @param $id
     */
    public function delete($id)
    {
        if ($this->user_model->destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 成为销售人员
     */
    public function write($id, $is_salesman = '')
    {

        if (!empty($id)) {
            $userModel = new \app\common\model\User();
            //$auth_group_access_model  = new AuthGroupAccessModel();
			
            if($is_salesman){
                if($userModel->where('id',$id)->update(['is_salesman' => 0])){
                    $this->success('操作成功');
                }else {
                    $this->error('操作失败1');
                }
            }else{
//                $user_info = $userModel->where('id',$id)->find();
//                if($auth_group_access_model->where('uid',$user_info['uid'])->find()){
//                    if($userModel->where('id',$id)->update(['is_author' => 1])){
//                        $this->success('操作成功');
//                    }else {
//                        $this->error('操作失败2');
//                    }
//                }else{
                    if($userModel->where('id',$id)->update(['is_salesman' => 1])){
                        $this->success('操作成功');
                    }else {
                        $this->error('操作失败3');
                    }

//                }
            }
			


            /*if ($userModel->saveAll($data)) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }*/
        } else {
            $this->error('请选择需要操作的用户');
        }
    }
}